package com.example.iot.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.iot.mapper.IotDataMapper;
import com.example.iot.pojo.IotDataObj;
import com.example.iot.pojo.jsonobj;
import com.example.iot.service.IotDataService;
import com.example.iot.util.Gettoken;
import com.example.iot.util.R;
import com.example.iot.util.TxtUtil;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author : Lin
 * @version : [v1.0]
 * @className : IotDataServiceImpl
 * @description : 描述说明该类的功能
 * @createTime : 2023/7/2 17:30
 * @updateUser : Lin
 * @updateTime : 2023/7/2 17:30
 * @updateRemark : 描述说明本次修改内容
 */
@Service
public class IotDataServiceImpl implements IotDataService {
    @Autowired
    IotDataMapper iotDataMapper;
    String sensorDeviceId="669655245830dc113eccd3bb_stm32_sensor";//传感器 设备id

    @Override
    public String RefreshToken(String name,String iamname,String pwd) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        String jsonString = JSON.toJSONString(Gettoken.GerRequestbody(name,iamname,pwd));
        RequestBody body = RequestBody.create(mediaType, jsonString);
        Request request = new Request.Builder()
                .url("https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens")
                .method("POST", body)
                .addHeader("Content-Type","application/json")
                .build();
        Response response = client.newCall(request).execute();
        String token = response.header("X-Subject-Token");

        String path="qiutoken.txt";
        TxtUtil.Write(path,token);
        return token;
    }

    @Transactional
    @Override
    public jsonobj.DeviceData GetAttributesFromPlatformByDeviceId(String deviceid) throws IOException {
        //球
        String token = TxtUtil.Read("qiutoken.txt");
        String instanceId="aa454fb4-b499-421f-80a4-6d19508a8afd";//实例ID
        String projectId="77023adedec742a89865c707f3254959";//项目id

        if (ObjectUtils.isEmpty(token)) {
            token = RefreshToken("liaolaolao","WANGYAN","WANGYAN123");
        }
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        String qianzui1="afed76c23e";
        String qianzui2="73794891aa";//两个url前缀都能访问
        /*String url="https://"+qianzui1+".st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/"+projectId+"/devices/"+deviceid+"/shadow";
        */
        String url="https://afed76c23e.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/77023adedec742a89865c707f3254959/devices/669655245830dc113eccd3bb_stm32_sensor/shadow";
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("X-Auth-Token", token)
                .addHeader("Instance-Id", instanceId)
                .addHeader("Content-Tpe", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        boolean successful = response.isSuccessful();
        if (!successful) {
            RefreshToken("liaolaolao","WANGYAN","WANGYAN123.");
            return null;
        }
        String bodystring = response.body().string();
        System.out.println(bodystring);
        //解析json数据
        jsonobj.DeviceData deviceData = JSON.parseObject(bodystring, jsonobj.DeviceData.class);
        return deviceData;
    }

    @Transactional
    @Override
    public R GetSensorData() throws IOException {
        jsonobj.DeviceData deviceData = GetAttributesFromPlatformByDeviceId(sensorDeviceId);
        if(ObjectUtils.isEmpty(deviceData)){
            return R.fail("获取数据失败");
        }
        // 访问Java对象中的数据
        String deviceId = deviceData.getDevice_id();
        List<jsonobj.ShadowData> shadows = deviceData.getShadow();
        IotDataObj dataobj = null;
        for (jsonobj.ShadowData shadowData : shadows) {
            String serviceId = shadowData.getService_id();
            jsonobj.ReportedData reportedData = shadowData.getReported();
            Map<String, Object> properties = reportedData.getProperties();
            String eventTime = reportedData.getEvent_time();
            // 创建日期格式化对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 格式化日期对象为字符串
            String timestamp = sdf.format(new Date(System.currentTimeMillis()));
            System.out.println(properties);
            Integer Distance =Integer.valueOf( properties.get("Distance").toString());
            Integer Humidity =Integer.valueOf( properties.get("Humidity").toString());
            Integer Temperature =Integer.valueOf( properties.get("Temperature").toString());
            Integer ZhuoDu =Integer.valueOf( properties.get("ZhuoDu").toString());
            double GPSN = Double.parseDouble(properties.get("GPSN").toString());
            double GPSE = Double.parseDouble(properties.get("GPSE").toString());
            dataobj = new IotDataObj(null,timestamp,Temperature,
                    Humidity,ZhuoDu,Distance,GPSN,GPSE);
        }
        AddIotData(dataobj);
        return R.ok(dataobj);
    }

    @Transactional
    @Override
    public void AddIotData(IotDataObj iotData){
        int insert = iotDataMapper.insert(iotData);
    }
    @Override
    public R ListAllIotData(){
        QueryWrapper<IotDataObj> queryWrapper = new QueryWrapper<IotDataObj>();
        //查询指定某字段以外的数据
        List<IotDataObj> iotDataObjs = iotDataMapper.selectList(queryWrapper);
        return R.ok(iotDataObjs);
    }
}
